package com.control.back.halo.bookmark.controller;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.control.back.halo.basic.controller.BaseController;
import com.control.back.halo.basic.entity.vo.TreeNode;
import com.control.back.halo.basic.json.Result;
import com.control.back.halo.basic.log4j.Logger;
import com.control.back.halo.bookmark.entity.Category;
import com.control.back.halo.bookmark.http.HttpRequest;
import com.control.back.halo.bookmark.json.Response;
import com.control.back.halo.bookmark.service.ICategoryService;
import com.control.back.halo.bookmark.service.IURLService;

@Controller
@RequestMapping("/category")
public class CategoryController extends BaseController {

    private static Logger    logger = Logger.getLogger(CategoryController.class);

    @Autowired
    private ICategoryService categorySerivce;

    @Autowired
    private IURLService      urlService;

    @RequestMapping(value = "/isConnection.json", produces = "application/json")
    public @ResponseBody Result isConnection(String urlAddress) {
        Result r = new Result();
        boolean flag = urlService.exists(urlAddress);
        r.setSuccess(flag);
        return r;
    }

    @RequestMapping(value = "/loadCategoryTree.json", produces = "application/json")
    public @ResponseBody List<TreeNode> loadCategoryTree() {
        return categorySerivce.loadCategoryTree();
    }

    @RequestMapping(value = "/insert.json", produces = "application/json")
    public @ResponseBody String insert(Category category) {
        try {
            categorySerivce.save(category);
        } catch (Exception e) {
            return "error";
        }
        return "success";
    }

    @RequestMapping(value = "/bookmarks.json", produces = "application/json")
    public @ResponseBody Result findBookmarks(Long parentId) {
        Result r = null;
        try {
            Category category = categorySerivce.find(parentId);
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("rootCategory", category);
            params.put("childs", category.getChildren());
            params.put("bookmarks", category.getMarks());
            r = new Result(true, "success", params);
        } catch (Exception ee) {
            r = Result.error("error:" + ee.getLocalizedMessage());
        }
        return r;
    }

    @RequestMapping("/index")
    public ModelAndView index() {
        return new ModelAndView("/category/index");
    }

    @RequestMapping("/repeatCategory")
    public String repeatCategory(Model model) {
        model.addAttribute("repeatCategorys", categorySerivce.findRepeatCategory());
        return "/category/repeatCategory";
    }

    @RequestMapping("/mergeCategory.json")
    public @ResponseBody Result mergeCategory(Long mId, String cIds) {
        boolean flag = categorySerivce.mergeCategory(mId, cIds);
        return new Result(flag, "merge", flag);
    }

    @RequestMapping("/rename.json")
    public @ResponseBody Result rename(Long id, String title, Long pid) {
        try {
            Category category = categorySerivce.find(id);
            if (category == null) {
                category = new Category();
                category.setParent(categorySerivce.find(pid));
            }
            category.setTitle(title);
            category.setTitleHashCode(title.trim().hashCode());
            category = categorySerivce.update(category);
            return new Result(true, "rename success", category.getId());
        } catch (Exception e) {
            logger.error("rename is error params [id:%s,title:%s,pid:%s]", e, id, title, pid);
        }
        return Result.error("error");
    }

    @RequestMapping("/onDrop.json")
    public @ResponseBody Result onDrop(String moveIds, Long parentId) {
        if (StringUtils.isNotBlank(moveIds)) {
            List<Category> categorys = categorySerivce.findCategoryByIds(moveIds);
            Category parent = categorySerivce.find(parentId);
            for (Iterator<Category> iterator = categorys.iterator(); iterator.hasNext();) {
                Category category = iterator.next();
                category.setParent(parent);
                categorySerivce.update(category);
            }
            return Result.success("drop success");

        }
        return Result.error("drop error");
    }

    @RequestMapping("/remove.json")
    public @ResponseBody Result remove(Long id) {
        Category category = categorySerivce.find(id);

        if (category == null) { return Result.success("删除成功!"); }

        if (category.getChildren() != null && !category.getChildren().isEmpty()) { return new Result(false, "分类下面存在子分类不允许删除!", null); }

        if (category.getMarks() != null && !category.getMarks().isEmpty()) { return new Result(false, "分类下面存在书签不允许删除!", null); }

        categorySerivce.delete(category);
        return Result.success("删除成功!");
    }

    @RequestMapping("/findCategoryByName.json")
    public @ResponseBody Response findCategoryByName(String q) {
        try {
            List<Category> categorys = categorySerivce.findCategoryByName(q);
            return new Response(true, "success", categorys);
        } catch (Exception e) {
            logger.error("find category error,params[name:%s]", e, q);
            return Response.error("error");
        }
    }

    @RequestMapping("/relChart")
    public String relChart() {
        return "/category/relChart";
    }

    @RequestMapping("/relChart/npm.json")
    public @ResponseBody JSONObject relNpm() {
        String jsonStr = HttpRequest.sendGet("http://echarts.baidu.com/data/asset/data/npmdepgraph.min10.json", null);
        JSONObject jsonObj = JSON.parseObject(jsonStr);
        return jsonObj;
    }
}
